const vscode = require('vscode')
const { getUrl } = require("./utils.js")
const { OpenInBrowser } = require('./openInBrowser.js');

/**
 * Think of a webview as an iframe within VS Code that your extension controls
 */
class OpenInEditor {
  constructor(panel, options) {
    this._disposables = [];
    this._panel = panel;
    this._options = options;
    // Set the webview's initial html content
    this._updateForCat();
    this._serializer()
    // Listen for when the panel is disposed
    // This happens when the user closes the panel or when the panel is closed programmatically
    this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
    // Update the content based on view changes
    this._panel.onDidChangeViewState(e => {
      if (this._panel.visible) {
        this._updateForCat();
      }
    }, null, this._disposables);
    // Handle messages from the webview
    this._panel.webview.onDidReceiveMessage(message => {
      if(message) {
        OpenInBrowser('', this._options)
      } 
      
    }, null, this._disposables);

    // Send a message to our webview.
    // currentPanel.webview.postMessage({ command: 'refactor' });
  }

  static createOrShow(options) {
    /*
    * TODO
    * column、currentPanel、dispose 
    */
    const column = vscode.window.activeTextEditor
      ? vscode.window.activeTextEditor.viewColumn
      : vscode.ViewColumn.One;
    // If we already have a panel, show it.
    // if (OpenInEditor.currentPanel) {
    //     OpenInEditor.currentPanel._panel.reveal(column);
    //     return;
    // }
    const panel = vscode.window.createWebviewPanel('UView', options.title, column, { enableScripts: true });
    OpenInEditor.currentPanel = new OpenInEditor(panel, options);
  }
  static revive(panel, options) {
    OpenInEditor.currentPanel = new OpenInEditor(panel, options);
  }

  dispose() {
    /**
     * TODO
     */
    OpenInEditor.currentPanel = undefined;
    // Clean up our resources
    this._panel.dispose();
    while (this._disposables.length) {
      const x = this._disposables.pop();
      if (x) {
        x.dispose();
      }
    }
  }

  _serializer() {
    if (vscode.window.registerWebviewPanelSerializer) {
      // Make sure we register a serializer in activation event
      vscode.window.registerWebviewPanelSerializer('UView', {
        async deserializeWebviewPanel(webviewPanel, state) {
          // console.log(`Got state: ${state}`);
          webviewPanel.webview.options = {}
          OpenInEditor.revive(webviewPanel, this._options);
        }
      });
    }
  }

  _updateForCat() {
    let url = getUrl(this._options)
    // vscode.window.showInformationMessage(url);
   
    this._panel.webview.html =  
      `
      <div style="width: calc(100vw - 55px); height: calc(100vh - 30px); position: relative;">
        <button style="position: absolute; bottom: 5px; right: 5px;" onclick="openInBrowser()">Open In Browser</button>
        <iframe 
          allowpaymentrequest=true
          src=${url}
          width="100%" 
          height="100%"
          frameborder="0">
        </iframe>
      </div>

      <script>
        const vscode = acquireVsCodeApi()
        function openInBrowser() {
          vscode.postMessage({
            command: 'openView-Node.js',
            text: 'open in browser'
          })
        }
      </script>
      `
  }
}

exports.OpenInEditor = OpenInEditor